package com.se.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.se.domain.mysql.ActivityDO;
import com.se.domain.mysql.QuestionDO;
import com.se.domain.request.param.CreateActParam;
import com.se.domain.request.param.QParam;
import com.se.domain.request.param.UpdateActParam;
import com.se.domain.vo.ResultVO;
import com.se.domain.vo.UrlCodeVO;
import com.se.enums.ResultCode;
import com.se.exception.ResultException;
import com.se.global.AuthHeaderRequestWrapper;
import com.se.service.ActPublishService;
import com.se.service.QrCodeService;
import com.se.util.MyDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@Slf4j
public class ActPublishController {
    @Autowired
    ActPublishService actPublishService;
    @Autowired
    QrCodeService qrCodeService;
    @Value("${url.http}")
    String httpPrefix;

    //测试成功的传参代码样例，勿删
//    @PostMapping("/must/act/create")
//    public ResultVO<Long> createAct(
//            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
//            @RequestPart(value = "act", required = false) CreateActParam createActParam,
//            @RequestPart(name = "file", required = false) MultipartFile file
//    ){
//        //测试参数获取，待删除
//        JSONObject jsonObject = new JSONObject(createActParam);
//        log.info(jsonObject.toString());
//        if(file != null){
//            log.info(file.getOriginalFilename());
//        }
//
//        return ResultVO.ok(null);
//    }

    @PostMapping("/must/act/create")
    public ResultVO<Long> createAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestPart(value = "act") @Validated CreateActParam param,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) throws ResultException {
        this.checkEditActParam(param);
        ActivityDO activityDO = actPublishService.createAct(param, files, userId);

        return ResultVO.ok(activityDO.getActId());
    }

    private void checkEditActParam(CreateActParam param) throws ResultException {
        //catId去重
        param.setCatIds(param.getCatIds().stream().distinct().toList());

        //日期检查
        SimpleDateFormat sdf = MyDateUtil.sdf;
        try {
            if(sdf.parse(param.getStartTime()).after(sdf.parse(param.getEndTime()))){
                throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "结束时间不能早于开始时间");
            }

            if(StrUtil.isBlank(param.getApplyTime())){
                param.setApplyTime(null);
            }else {
                sdf.parse(param.getApplyTime());
            }
            if(StrUtil.isBlank(param.getApplyEndTime())){
                param.setApplyEndTime(null);
            }else {
                sdf.parse(param.getApplyEndTime());
            }
        } catch (ParseException e) {
            throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "日期格式错误");
        }
        //size检查
        if(param.getSize() == 0){
            throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "数量不能为0");
        }

        //qn检查
        if(!param.getQn().isEmpty()){
            for (QParam qParam : param.getQn()) {
                switch (qParam.getType()){
                    case QuestionDO.Type.FILL -> {
                        qParam.setOptions(null);
                    }
                    case QuestionDO.Type.SINGLE, QuestionDO.Type.MULTI -> {
                        if (qParam.getOptions().isEmpty()){
                            throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "选项不能为空");
                        }
                    }
                }
            }
        }
    }

    @PostMapping("/must/act/update")
    public ResultVO<Void> updateAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestPart(value = "act") @Validated UpdateActParam updateActParam,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) throws ResultException {
        this.checkEditActParam(updateActParam);
        actPublishService.updateAct(updateActParam,files, userId);
        return ResultVO.ok(null);
    }

    @PostMapping("/must/act/publish")
    public ResultVO<UrlCodeVO> publishAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestParam Long actId
    ) throws ResultException, IOException, ParseException {
        actPublishService.publishAct(actId, userId);
        //二维码，网址
        String url = this.httpPrefix + "/act/info?actId="+actId;
        String base64 = qrCodeService.base64(url);
        return ResultVO.ok(new UrlCodeVO(url, base64));
    }

    @PostMapping("/must/act/publish/cancel")
    public ResultVO<Void> cancelPublishAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestParam Long actId
    ) throws ResultException, ParseException, IOException {
        actPublishService.cancelPublishAct(actId, userId);

        return ResultVO.ok(null);
    }

    @PostMapping("/must/act/delete")
    public ResultVO<Void> deleteAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestParam Long actId
    ) throws ResultException {
        actPublishService.deleteAct(actId, userId);
        return ResultVO.ok(null);
    }
}
